﻿using Model;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;

namespace Business
{
    public class RoleBiz
    {
        public int SaveItem(Role item)
        {
            var dbContext = new Context();

            dbContext.Roles.Add(item);
            dbContext.SaveChanges();

            return item.Id;
        }

        public void UpdateItem(Role item)
        {
            var dbContext = new Context();
            dbContext.Entry(item).State = EntityState.Modified;
            dbContext.SaveChanges();
        }

        public Role LoadItem(int id)
        {
            var dbContext = new Context();
            return (from item in dbContext.Roles
                    where item.Id == id
                    select item).First();
        }

        public Role LoadItem(string name)
        {
            var dbContext = new Context();
            return (from item in dbContext.Roles
                    where item.Name == name
                    select item).First();
        }

        public void RemoveItem(List<Role> items)
        {
            var dbContext = new Context();

            string ids = string.Empty;

            foreach (var item in items)
            {
                ids += item.Id + ",";
            }

            if (ids.EndsWith(","))
            {
                ids = ids.Substring(0, ids.Length - 1);

                string deleteCommand = string.Format(Constants.DeleteCommand, "Role", ids);
                dbContext.Database.ExecuteSqlCommand(deleteCommand);
            }   
        }

        public List<Role> LoadItems()
        {
            var dbContext = new Context();
            return (from item in dbContext.Roles
                    select item).OrderBy(item => item.Name).ToList();
        }

        public bool SearchByName(string name, int id)
        {
            var dbContext = new Context();
            var result = (from item in dbContext.Roles
                          where item.Name.ToLower() == name.ToLower()
                          select item).ToList();

            if (result != null && result.Count > 0)
            {
                if(id > 0)
                {
                    return result[0].Id != id;
                }
                return true;
            }

            return false;
        }
    }
}
